package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.MainActivity;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.dialog.CustomDialog;
import com.tsinghuabigdata.edu.ddmath.fragment.MyBaseFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.EditPersonalinfoFragment;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.EditUserHeaderActivity;
import com.tsinghuabigdata.edu.ddmath.module.mycenter.SetHeadImage;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.UploadManager;
import com.tsinghuabigdata.edu.ddmath.requestHandler.MycenterReqService;
import com.tsinghuabigdata.edu.ddmath.requestHandler.requestImpl.MycenterReqImpl;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.GlobalData;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;
import com.tsinghuabigdata.edu.ddmath.util.ValidatorUtils;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;

import roboguice.inject.InjectView;


/**
 * 个人中心
 * Created by Administrator on 2016/12/14.
 */

public class UsercenterFragment extends MyBaseFragment implements View.OnClickListener {
    private static final String TAG = "UsercenterFragment";
    public static final int EDIT = 1;
    public static final int ADD_PERSONALINFO = 2;
    private View root;

    @InjectView(R.id.civ_head)
    private CircleImageView civHead;

    @InjectView(R.id.tv_name)
    private TextView tvName;
    @InjectView(R.id.tv_quit)
    private TextView tvQuit;

    //title
    @InjectView(R.id.tv_phone)
    private TextView tvPhone;
    @InjectView(R.id.tv_gender)
    private TextView tvGender;
    @InjectView(R.id.tv_reallyname)
    private TextView tvReallyname;
    @InjectView(R.id.tv_encrollyears)
    private TextView tvEncrollyears;

    //val
    @InjectView(R.id.tv_phonev)
    private TextView tvPhonev;
    @InjectView(R.id.tv_genderv)
    private TextView tvGenderv;
    @InjectView(R.id.tv_reallynamev)
    private TextView tvReallynamev;
    @InjectView(R.id.tv_encrollyearsv)
    private TextView tvEncrollyearsv;

    @InjectView(R.id.tv_edit)
    private TextView tvEdit;

    private MainActivity mainActivity;

    // 1 编辑  2 添加个人信息
    private int editState = EDIT;

    private MyProgressDialog progressDialog;

    private UserDetailinfo userDetailinfo;

    private Bitmap mHeadImage;
    private boolean isFinishing;
    private MycenterReqService mycenterReqService = new MycenterReqImpl();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_usercenter, container, false);
        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }


    private void initView() {
        userDetailinfo = AccountUtils.getUserdetailInfo();

        progressDialog = new MyProgressDialog(getContext());

        civHead.setOnClickListener(this);

        mainActivity = (MainActivity) getActivity();

        tvQuit.setOnClickListener(this);
        tvEdit.setOnClickListener(this);

        showDetailInfo();

    }

    private void showDetailInfo() {
        if (userDetailinfo == null) {
            return;
        }
        tvName.setText(userDetailinfo.getNickName());
        tvPhonev.setText(userDetailinfo.getPhone());
        tvGenderv.setText(userDetailinfo.getSex());

        if (isRealnameEmpty() && TextUtils.isEmpty(userDetailinfo.getSchoolName())
                && TextUtils.isEmpty(userDetailinfo.getSerial())) {
            editState = ADD_PERSONALINFO;
        } else {
            editState = EDIT;
        }

        if (editState == ADD_PERSONALINFO) {
            tvEdit.setText("添加个人信息");
            showExtraInfo(false);
        } else {
            tvEdit.setText("编辑");
            showExtraInfo(true);
        }
    }

    private boolean isRealnameEmpty() {
        if (TextUtils.isEmpty(userDetailinfo.getReallyName())) {
            return true;
        } else if (ValidatorUtils.validateMobile(userDetailinfo.getReallyName())) {
            return true;
        }
        return false;
    }

    private void showExtraInfo(boolean isshow) {
        if (isshow) {
            tvReallyname.setVisibility(View.VISIBLE);
            tvReallynamev.setVisibility(View.VISIBLE);
            tvEncrollyears.setVisibility(View.VISIBLE);
            tvEncrollyearsv.setVisibility(View.VISIBLE);

            tvReallynamev.setText(userDetailinfo.getReallyName());
            tvEncrollyearsv.setText(userDetailinfo.getSerial());
        } else {
            tvReallyname.setVisibility(View.INVISIBLE);
            tvReallynamev.setVisibility(View.INVISIBLE);
            tvEncrollyears.setVisibility(View.INVISIBLE);
            tvEncrollyearsv.setVisibility(View.INVISIBLE);
        }
    }

    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_quit:
                quitApp();
                break;
            case R.id.civ_head:
                Intent intent = new Intent(getContext(), EditUserHeaderActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_edit:
                edit();
                break;
        }
    }

    private void quitApp() {
        CustomDialog customDialog = AlertManager.showCustomDialog(getContext(), "退出登录？", "退出", "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                progressDialog.setMessage("正在退出...");
                progressDialog.show();
                new LoginModel().logout(AccountUtils.getLoginUser().getAccessToken(), new RequestListener() {
                    @Override
                    public void onSuccess(Object res) {

                        UploadManager uploadManager = UploadManager.getUploadManager();
                        if( uploadManager != null) uploadManager.stopAllUploadTask();

                        progressDialog.dismiss();
                        Log.d(TAG, "onSuccess: ");
                        AccountUtils.clear();
                        finish();
                        mainActivity.setHead(null);
                        GlobalData.setLoginChange(true);
                        PreferencesUtils.removeSharedPreferenceByKey(mainActivity, AppConst.IS_USERCENTER_SHOW);
                    }

                    @Override
                    public void onFail(HttpResponse response, Exception ex) {
                        progressDialog.dismiss();
                        AccountUtils.clear();
                        finish();
                        mainActivity.setHead(null);
                    }
                });
            }
        }, null);
        customDialog.setRightBtnAttr(R.drawable.bg_rect_blue_r24, R.color.white);
    }

    private void edit() {
        finish();
        goFragment(new EditPersonalinfoFragment());
    }

    @Override
    public void onResume() {
        super.onResume();
        //在跳到其他activity后，状态会改变,因此可在此及时更新修改头像后的个人信息
        Log.d(TAG, "onResume: ");

        userDetailinfo = AccountUtils.getUserdetailInfo();
        if (userDetailinfo != null) {
            SetHeadImage.setHeadImage(getContext(), civHead, userDetailinfo);
            mainActivity.setHead(userDetailinfo);
            showDetailInfo();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFinishing = true;
        Log.d(TAG, "onDestroyView: us");
    }
}
